
/**
 * @description 处理全局事件总线
 * */
class EventBus {
	events: Map<string, Array<Function>>
	constructor() {
		this.events = new Map<string, Array<Function>>()
	}
	/**
	 * @description 监听事件
	 * */
	on(name: string, callback: Function) {
		if (!this.events.has(name)) this.events.set(name, []);
		this.events.get(name)!!.push(callback);
	}
	/**
	 * @description 派发事件
	 * */
	emit(name: string, ...args: any[]) {
		if (!this.events.has(name)) return;
		this.events.get(name)!!.forEach(ele => {
			ele.apply(this, args);
		})
	}
	/**
	 * @description 清空全部事件
	 * */
	clear() {
		this.events = new Map<string, Array<Function>>();
	}
	/**
	 * @description 注销事件
	 * */
	off(name: string, callback: Function) {
		if (!this.events.has(name)) return;
		this.events.set(name, this.events.get(name)!!.filter(cb => cb != callback));
		if (this.events.get(name)!!.length == 0) this.events.delete(name);
	}
	/**
	 * @description 只监听一次
	 * */
	once(name: string, callback: Function) {
		const fn = (...args: any[]) => {
			callback(args);
			this.off(name, fn);
		}
		this.on(name, fn);
	}
}
export default new EventBus();